/**
 * create by young (young2f@outlook.com) on 2020/9/16
 * 添加客户实验记录
 */


'use strict';
import React from 'react';
import {
  AutoComplete,
  Button,
  Card,
  DatePicker,
  Form,
  Input,
  InputNumber,
  notification,
  Popconfirm,
  Select,
  Table
} from 'antd';

import {FormField, FormLayout, ModalFooter, ModalView} from 'antd-extra';
import FormBase from '../../../components/Base/FormBase';
import {connect} from "dva";
import moment from 'moment';
import 'moment/locale/zh-cn';

import ViewTitle from "../../../components/ViewTitle";
import styles from "../../index.less";
import ModalCreateOrEdit2 from "../../dic/modal/ModalCreateOrEdit2";
import UploadPic from "../../../components/UploadPic";
import ModalCreateOrEditConclusion from "./ModalCreateOrEditConclusion";
import ModalCreateOrEditStep from "./ModalCreateOrEditStep";

moment.locale('zh-cn');

@Form.create()
@connect(({
            tenant,
            global,
            customer,
            dic
          }) => ({...tenant, ...dic, ...customer, ...global}))
export default class ModalCreateOrEditCustomerRecord extends FormBase {
  constructor(props) {
    super(props);
    const {record = {}} = this.props;
    this.state = {...record};

  }

  componentDidMount() {
    this.props.dispatch({
      type: 'global/getModel',
      payload: {table: 'ExperimentRecord'}
    });
    this.props.dispatch({
      type: 'customer/findMany',
      payload: {}
    });
  }

  renderFoot = () => {
    const {foot, value, callback, modalRef, record, form} = this.props;

    if (foot) {
      return foot(value, modalRef);
    } else {
      return (
        <ModalFooter>
          <Button type="primary" onClick={() => {
            form.validateFields((err, values) => {
              if (err) {
                const {code} = err;
                const {errors} = code;
                errors.forEach(item => {
                  notification.error(item);
                });
                return;
              }
              values.code = record ? record.code : "ESP" + moment().format('YYYYMMDDHHmmss');
              const {fileList, steps, conclusions} = this.state;
              values.fileList = fileList;
              values.steps = steps;
              values.conclusions = conclusions;
              callback(values);
              modalRef.close();
            });

          }}>确定</Button>
          <Button onClick={() => {
            modalRef.close();
          }}>取消</Button>
        </ModalFooter>
      );
    }
  };
  onCreateOrEditStep = (record) => {
    const title = record ? "编辑" : "添加";
    ModalView.open(ModalCreateOrEditStep,
      {
        title,
        width: '1080px'
      }, {
        record,
        callback: async (payload) => {
          if (record) {
            _.map(this.state.steps, (item, key) => {
              if (item.code === record.code) {
                const {steps} = this.state;
                this.state.steps[key] = {...steps[key], ...payload};
              }
            });
            this.componentDidMount();
            return;
          }
          this.state.steps.push(payload);
          this.componentDidMount();
        }
      });
  };

  cols() {
    return [
      {title: '实验水量', dataIndex: 'water', key: 'water'},
      {title: 'a药剂', dataIndex: 'ayj', key: 'ayj'},
      {title: 'b药剂', dataIndex: 'byj', key: 'byj'},
      {title: 'c药剂', dataIndex: 'cyj', key: 'cyj'},
      {title: 'd药剂', dataIndex: 'dyj', key: 'dyj'},

      {
        title: '操作', dataIndex: 'opt', key: 'opt', render: (value, record) => {
          return <span>
        <a style={{marginRight: '6px'}}
           onClick={() => this.onCreateOrEditStep(record)}
        >编辑</a>
        <Popconfirm
          title="确认删除"
          onConfirm={() => {
            const temp = [];
            _.map(this.state.steps, (item, key) => {
              if (item.code !== record.code) {
                temp.push(item);
              }
            });
            this.state.steps = temp;
            this.componentDidMount();
          }}
          okText="是"
          cancelText="否"
        >
            <a>删除</a>
          </Popconfirm>
      </span>;
        }
      }
    ];
  }

  onCreateOrEditConclusion = (record) => {
    const title = record ? "编辑" : "添加";
    ModalView.open(ModalCreateOrEditConclusion,
      {
        title,
        width: '920px'
      }, {
        record,
        callback: async (payload) => {
          if (record) {
            _.map(this.state.conclusions, (item, key) => {
              if (item.code === record.code) {
                const {conclusions} = this.state;
                this.state.conclusions[key] = {...conclusions[key], ...payload};
              }
            });
            this.componentDidMount();
            return;
          }
          this.state.conclusions.push(payload);
          this.componentDidMount();
        }
      });
  };

  tableCols() {
    return [
      {
        title: '实验日期', dataIndex: 'date', key: 'date', width: 150, render: (value, record) => {
          return <div>{moment(value).format('YYYY-MM-DD')}</div>;
        }
      },
      {title: '操作者', dataIndex: 'user', key: 'user', width: 100},
      {title: '结论内容', dataIndex: 'conclusion', key: 'conclusion'},
      {
        title: '操作', dataIndex: 'opt', key: 'opt', width: 100, render: (value, record) => {
          return <span>
        <a style={{marginRight: '6px'}}
           onClick={() => this.onCreateOrEditConclusion(record)}
        >编辑</a>
        <Popconfirm
          title="确认删除"
          onConfirm={() => {
            const temp = [];
            _.map(this.state.conclusions, (item, key) => {
              if (item.code !== record.code) {
                temp.push(item);
              }
            });
            this.state.conclusions = temp;
            this.componentDidMount();
          }}
          okText="是"
          cancelText="否"
        >
            <a>删除</a>
          </Popconfirm>
      </span>;
        }
      }
    ];
  }

  render() {
    const {form, customers = [], record = {}} = this.props;
    const {
      customer,
      experimentType,
      salesman,
      customerDesc,
      experimentMan,
      experimentRequire,
      memo, date
    } = record;
    const _date = date ? moment(date) : moment();
    const {conclusions, steps, fileList = []} = this.state;
    if (!conclusions) this.state.conclusions = [];
    if (!steps) this.state.steps = [];
    const model = this.props[`ExperimentRecordModel`];
    // const {aFileList, bFileList, cFileList, sFileList} = record;
    _.map(model, (item, key) => {
      item.key = key;
    });

    return (
      <div>
        <FormLayout form={form} cols={2}>
          <FormField label={'客户'}
                     name={'customer'}
                     required={true}
                     initialValue={customer}
          >
            <AutoComplete style={{width: '100%'}}
                          dataSource={this.getOpt('customer', customers)}
                          filterOption={(inputValue, option) =>
                            option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
                          }
                          allowClear
              // onSelect={this.onSelectCustomer}
            >
            </AutoComplete></FormField>
          <FormField label={'实验类型'}
                     name={'experimentType'}
                     required={true}
                     initialValue={experimentType}
          >
            <Select style={{width: '100%'}} allowClear>
              {[<Select.Option value={"污水"}>{"污水"}</Select.Option>,
                <Select.Option value={"循环水"}>{"循环水"}</Select.Option>,
                <Select.Option value={"循环水"}>{"循环水"}</Select.Option>,
                <Select.Option value={"反渗透水"}>{"反渗透水"}</Select.Option>,
                <Select.Option value={"锅炉水"}>{"锅炉水"}</Select.Option>,
                <Select.Option value={"其它"}>{"其它"}</Select.Option>]}
            </Select>
          </FormField>
          <FormField label={'日期'}
                     name={'date'}
                     required={true}
                     initialValue={_date}
          >
            <DatePicker></DatePicker>
          </FormField>

          <FormField label={'业务员'}
                     name={'salesman'}
                     required={true}
                     initialValue={salesman}
          >
            <Input></Input>
          </FormField>
          <FormField label={'实验员'}
                     name={'experimentMan'}
                     required={true}
                     initialValue={experimentMan}
          >
            <Input></Input>
          </FormField>
          <FormField label={'客户困扰描述'}
                     name={'customerDesc'}
                     initialValue={customerDesc}
          >
            <Input.TextArea></Input.TextArea>
          </FormField>
          <FormField label={'实验要求及标准描述'}
                     name={'experimentRequire'}
                     initialValue={experimentRequire}
          >
            <Input.TextArea></Input.TextArea>
          </FormField>
          <FormField label={'备注'}
                     name={'memo'}
                     initialValue={memo}
          >
            <Input.TextArea></Input.TextArea>
          </FormField>
        </FormLayout>
        <UploadPic title={"参数调查表"} fileList={fileList}
                   callback={f => this.setState({fileList: f.fileList})}> </UploadPic>
        <ViewTitle title={'实验步骤'} actions={<Button type={'primary'} onClick={() => {
          this.onCreateOrEditStep();
        }}>添加</Button>}></ViewTitle>
        <Table
          className={styles.antTable}
          bordered={true}
          columns={this.cols()}
          dataSource={steps}
          scroll={{x: true}}
          pagination={true}
        ></Table>
        <ViewTitle title={'结论'} actions={<Button type={'primary'} onClick={() => {
          this.onCreateOrEditConclusion();
        }}>添加</Button>}></ViewTitle>
        {
          <Table
            className={styles.antTable}
            bordered={true}
            columns={this.tableCols()}
            dataSource={conclusions}
            scroll={{x: true}}
            pagination={true}
          ></Table>
        }
        {this.renderFoot()}
      </div>
    );
  }
}

